/**
 * 
 */
package cn.terrence.myrpc.common.serializable.impl;

import java.io.InputStream;
import java.io.OutputStream;

import cn.terrence.myrpc.common.serializable.CoderContext;
import cn.terrence.myrpc.common.serializable.CoderException;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
/**
 * 
 * @author Terrence2013
 * 2018年1月19日 下午1:50:40
 * Kryo序列化实现
 */
public class KryoCoder extends AbsCoder {

	public KryoCoder(CoderContext context){
		super(context);
	}

	@Override
	public void code(OutputStream outputStream,Object object) throws CoderException{
		Output output = null;
	 try {
		  Kryo kryo = new Kryo();
		  output = new Output(outputStream);
	      kryo.writeObject(output, object);
	      output.flush();
	      output.close();
	    } catch (Exception e) {
	    	throw new CoderException(e);
	    } finally{
	    	if(null!=output){
	    		output.close();
	    	}
	    }
	}
	
	@Override
	public <T>T decode(InputStream inputStream,Class<T> clazz)throws CoderException{
		T returnObj = null;
		Input input = null;
	    try {
	       Kryo kryo = new Kryo();
	       input = new Input(inputStream);
	       returnObj = (T)kryo.readObject(input, clazz);
	    } catch (Exception e) {
	    	throw new CoderException(e);
	    } finally{
	    	if(null!=input){
	    		input.close();
	    	}
	    }
	    return returnObj;
	}

}
